const pool = require('../config/db');
const { v4: uuidv4 } = require('uuid');

const Bookmark = {
    async create({ user_id, post_id }) {
        const bookmark_id = uuidv4();
        await pool.query(
            'INSERT INTO bookmarks (bookmark_id, user_id, post_id) VALUES (?, ?, ?)',
            [bookmark_id, user_id, post_id]
        );
        return { bookmark_id };
    },

    async delete(user_id, post_id) {
        await pool.query('DELETE FROM bookmarks WHERE user_id = ? AND post_id = ?', [user_id, post_id]);
    },

    async findByUserId(user_id, limit = 10, offset = 0) {
        const [rows] = await pool.query(
            'SELECT p.*, ps.likes_count, ps.comments_count, ps.shares_count FROM bookmarks b JOIN posts p ON b.post_id = p.post_id LEFT JOIN post_stats ps ON p.post_id = ps.post_id WHERE b.user_id = ? AND p.is_active = TRUE ORDER BY b.created_at DESC LIMIT ? OFFSET ?',
            [user_id, limit, offset]
        );
        return rows;
    }
};

module.exports = Bookmark;